package com.longlonggo.action;

import com.longlonggo.action.BaseAction;
import com.longlonggo.constant.Constant;
import com.longlonggo.entity.PermissionEntity;
import com.longlonggo.entity.UserEntity;
import com.longlonggo.service.PermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录控制层
 *
 * @author 石马人山 me@longlonggo.com
 * @version 100-000-000<br/>
 * @Created 2018年4月26日 下午4:05:16
 * </p>
 * @description <br/>
 */
//shiro配置参考 https://blog.csdn.net/u013615903/article/details/78781166
@Controller
@RequestMapping("/")
public class LoginAction extends BaseAction {

    @Autowired
    PermissionService permissionService;

    /**
     * 登录页
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(HttpServletRequest request, Model model) {
        Subject currentUser = SecurityUtils.getSubject();
        if (currentUser.isAuthenticated() || currentUser.isRemembered()) {
            return "redirect:/index";
        }
        return "/login";
    }

    /**
     * 主页
     *
     * @param request
     * @param model
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("permissionStatus", Constant.PERMISSION_STATUS_0);
        map.put("permissionType", Constant.PERMISSION_TYPE_1);
        map.put("permissionIsMenu", Constant.PERMISSION_IS_MENU_0);
        List<PermissionEntity> menuList = (List<PermissionEntity>) permissionService.queryListByMap(map);
        model.addAttribute("menuList", menuList);

        logger.info("----进入主页---");
        return "/index";
    }

    /**
     * 执行登录
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String baseRetrun(@ModelAttribute UserEntity user, HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getUserPassword());

        try {
            subject.login(token);
//            if (subject.isAuthenticated() || subject.isRemembered()) {            
            request.setAttribute("token", subject.getSession().getId());
            request.setAttribute("msg", "登录成功");
            logger.debug("---------登录成功");
            return "redirect:/index";
//    		}
        } catch (IncorrectCredentialsException e) {
            logger.debug("---------密码错误");
            request.setAttribute("msg", "密码错误");
        } catch (LockedAccountException e) {
            logger.debug("---------登录失败，该用户已被冻结");
            request.setAttribute("msg", "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            logger.debug("---------该用户不存在");
            request.setAttribute("msg", "该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/login";
    }

    /**
     * 登出
     *
     * @param userName
     * @param model
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/login";
    }


    @RequestMapping(value = "/error/{code}")
    public String error(@PathVariable int code, Model model) {
        String pager = "/error/404";
        switch (code) {
            case 403:
                model.addAttribute("code", 403);
                pager = "/error/403";
                break;
            case 404:
                model.addAttribute("code", 404);
                pager = "/error/404";
                break;
            case 500:
                model.addAttribute("code", 500);
                pager = "/error/500";
                break;
        }
        return pager;
    }

}
